<?php
declare (strict_types = 1);
namespace app\api\logic;

use app\api\error\Oauth as OauthResponse;
use think\facade\Request;
use Firebase\JWT\JWT;
use think\facade\Config;
use think\facade\Cache;

class Oauth extends ApiBase {

    private $expire_in = 604800;

    private $refresh_expire_in = 2419200;

    protected $url = '';

    /**
     * 白名单，也可以不适用，后期开发人员到路由中使用中间件替代
     * @return bool
     */
    private function checkWhite(){
        $this->url = Request::baseUrl();
        $white_list = Config::get('white.' . Request::subDomain());
        return in_array($this->url, $white_list);
    }
    /**
     * 验证access_token
     * @param array $param
     * @param string $type
     * @return array
     */
    public function checkToken(): void{
        if ($this->checkWhite()) return;
        $header = Request::header();
        $access_token = $header['access-token'] ?? '';
        empty($access_token) && $this->responseData(OauthResponse::$loseAccessToken);
        $access_token_val = Cache::store('redis')->get($access_token);
        empty($access_token_val) && $this->responseData(OauthResponse::$wrongToken);
        $key = API_KEY . JWT_KEY;
        $decodeToken = JWT::decode($access_token_val,$key, array('HS256'));
        (!is_object($decodeToken) || empty($decodeToken->data)) &&  $this->responseData(OauthResponse::$parseTokenFailed);
        self::$userInfo = json_decode(json_encode($decodeToken),true);
    }

    /**
     * 验证权限
     * @param array $param 请求参数
     * @return array
     */
    public function checkAuth(): void{
        if ($this->checkWhite()) return;
        $userInfo = self::$userInfo;
        $auths = $userInfo['auths'];
        !in_array($this->url,$auths) && $this->responseData(OauthError::$Unauthorized);
    }
}
